package com.stylefeng.guns.util;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import java.io.IOException;
public class AppPush {
    //定义常量, appId、appKey、masterSecret 采用本文档 "第二步 获取访问凭证 "中获得的应用配置
    private static String appId = "hSqOqRDVZx5gDzGeW92dp1";
    private static String appKey = "zG5MTY5M8D9y4YrCZLAKL1";
    private static String AppSecret ="fZSJJHIsFu5vC4UYl27rS9";
    private static String masterSecret = "ahf6hffsha8xNpMrUFfoW4";
    private static String url = "http://sdk.open.api.igexin.com/apiex.htm";

    public static void main(String[] args) throws IOException {
        try {
            sendmsg("{'ope':'add'}", "fd50b90107a7d0adf242d65048685229");
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
    public static void sendmsg(String content,String cId) throws Exception{
        IGtPush push = new IGtPush(url, appKey, masterSecret);
        TransmissionTemplate template=transmissionTemplateDemo(content);
        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cId);
        //target.setAlias(Alias);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            System.out.println("服务器响应异常");
        }
    }
    private  static TransmissionTemplate transmissionTemplateDemo(String content) {
        if(content.length()<2048){
            TransmissionTemplate template = new TransmissionTemplate();
            template.setAppId(appId);
            template.setAppkey(appKey);
            // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
            template.setTransmissionType(2);
            template.setTransmissionContent(content);
            return template;

        }else{
            throw new  RuntimeException("内容长度不超过2048！");
        }
    }
}
